package jinyilw.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

//一个参数的通用执行接口集合
public class OperatorSets<T>
{
	private volatile List<Operator<T>> operators;
	private boolean threadSafe;

	public OperatorSets()
	{
	}

	public OperatorSets(boolean threadSafe)
	{
		this.threadSafe = threadSafe;
	}

	public void add(Operator<T> operator)
	{
		if (operators == null)
			createOperators();
		if (!operators.contains(operator))
			operators.add(operator);
	}

	public void remove(Operator<T> operator)
	{
		if (operators != null)
			operators.remove(operator);
	}

	public void operate(T o)
	{
		if (operators != null)
			for (Operator<T> operator : operators)
				operator.operate(o);
	}

	private synchronized void createOperators()
	{
		if (operators == null)
		{
			operators = new ArrayList<>();
			if (threadSafe)
				operators = Collections.synchronizedList(operators);
		}
	}
}
